package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.CollectBean;
import com.mlz.mlzmall.bean.CollectBean.DataBean;
import com.mlz.mlzmall.bean.CollectBean.DataBean.ListBean;
import com.mlz.mlzmall.bean.StatusBean;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.GoogDetailsActivity;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.adapter.base.BaseMallAdapter;
import com.mlz.mlzmall.ui.dialog.ReuestDialog;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.LogUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/18.
 */
public class CollectActivity extends VolleyBaseActivity {


    private GridView gv_collection;//我的收藏
    private boolean isSet;
    private CollectAdapter adapter;
    private List<ListBean> list;
    private RelativeLayout rl_collection_null;
    private TextView top_right_title;

    public void Back(View v) {
        finish();
        CollectActivity.this.overridePendingTransition(R.anim.right_in, R.anim.right_out);
    }

    public void setRightTitle(View v) {
        if (isSet) {
            top_right_title.setText(getString(R.string.complete));
            isSet = false;
            adapter.setDel(true);
            LogUtils.d("2" + isSet);
        } else {
            top_right_title.setText(getString(R.string.edit));
            isSet = true;
            adapter.setDel(false);////////null
            LogUtils.d("1" + isSet);

        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_collect);//跳转到我的收藏界面
        initView();
        getCollectData();
    }


    /**
     * 初始化
     */
    private void initView() {
        TextView title = (TextView) findViewById(R.id.top_title);
        top_right_title = (TextView) findViewById(R.id.top_right_title);
        title.setText("我的收藏");
        top_right_title.setVisibility(View.VISIBLE);
        gv_collection = (GridView) findViewById(R.id.gv_collection);
        rl_collection_null = (RelativeLayout) findViewById(R.id.rl_collection_null);
    }

    /**
     * 请求收藏的数据
     */
    private void getCollectData() {
        ReuestDialog.showProgressDialog(CollectActivity.this);//显示加载框
        //获取我的收藏数据
        tag = "getCollectData";
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("telephone", isNull(MyApplication.getInstance().getLoginUser().getAccout()));
        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.WISHLIST.LIST, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                ReuestDialog.dissmissProgressDialog();//关闭加载框
                Log.e(tag, jsonObject.toString());
                Gson gson = new Gson();
                CollectBean userInfo = gson.fromJson(jsonObject.toString(), CollectBean.class);
                DataBean db = userInfo.getData();
                if (userInfo.getStatus() == 0 && db.getTotal() != 0) {
                    list = db.getList();
                    initOnItemClickListener();
                    rl_collection_null.setVisibility(View.GONE);
                    gv_collection.setVisibility(View.VISIBLE);
                } else {
                    rl_collection_null.setVisibility(View.VISIBLE);
                    gv_collection.setVisibility(View.GONE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
                ReuestDialog.dissmissProgressDialog();//关闭加载框
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);

    }

    /**
     * 下面的代码是设置GridView数据和监听事件
     */
    private void initOnItemClickListener() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        } else {
            adapter = new CollectAdapter(this, list, R.layout.my_collect_item_layout);
            gv_collection.setAdapter(adapter);
        }
        gv_collection.setVisibility(View.VISIBLE);
        gv_collection.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(CollectActivity.this, GoogDetailsActivity.class);
                intent.putExtra("productId", list.get(position).getProductId());
                startActivity(intent);
                CollectActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
            }
        });
    }


    private class CollectAdapter extends BaseMallAdapter {
        private final int id_layout;
        private final List<ListBean> list;
        private final Context context;
        private boolean isDel = false;

        public boolean isDel() {
            return isDel;
        }

        public void setDel(boolean del) {
            isDel = del;
        }

        public CollectAdapter(Context context, List<ListBean> list, int my_collect_item_layout) {
            this.list = list;
            this.id_layout = my_collect_item_layout;
            this.context = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public View getView(final int position, View convert, ViewGroup parent) {
            ViewHolder holder;
            if (convert == null) {
                holder = new ViewHolder();
                convert = LayoutInflater.from(context).inflate(id_layout, null);
                holder.picture = (ImageView) convert.findViewById(R.id.iv_collection_picture);
                holder.name = (TextView) convert.findViewById(R.id.tv_shop_name);
                holder.shop_price = (TextView) convert.findViewById(R.id.tv_shop_price);
                holder.price = (TextView) convert.findViewById(R.id.tv_price);
                holder.del = (ImageView) convert.findViewById(R.id.img_del);
                convert.setTag(holder);
            } else {
                holder = (ViewHolder) convert.getTag();
            }
            //将图片显示任务添加到执行池，当轮到此ImageView图片将会显示imageView
            imageLoader.displayImage(list.get(position).getImage(), holder.picture, options);
            holder.name.setText(list.get(position).getName());
            holder.shop_price.setText("专柜价" +getString(R.string.money_k)+getString(R.string.money_f)+ list.get(position).getRefPrice());
            holder.price.setText(getString(R.string.money_f)+getString(R.string.money_k)+ list.get(position).getPrice());
            if (!isDel) {
                holder.del.setVisibility(View.GONE);
            } else {
                holder.del.setVisibility(View.VISIBLE);
            }
            holder.del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DelCollectData(list.get(position).getProductId());//删除收藏的数据
                    list.remove(position);
                    if (list.size() == 0) {
                        rl_collection_null.setVisibility(View.VISIBLE);
                        gv_collection.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
                }
            });

            return convert;
        }


        private class ViewHolder {
            public ImageView picture;
            public TextView name;
            public TextView shop_price;
            public TextView price;
            public ImageView del;
        }
    }

    /**
     * 下面的代码是删除收藏的数据
     *
     * @param productId
     */
    private void DelCollectData(int productId) {
        tag = "DelCollectData";
        Map<String, String> param1 = new HashMap<>();
        param1.put("productId", productId + "");
        JSONObject jsonObject = new JSONObject(param1);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.WISHLIST.REMOVE, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Gson gson = new Gson();
                StatusBean sb = gson.fromJson(jsonObject.toString(), StatusBean.class);
                if (sb.getStatus() == 0) {
                    showToast(sb.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }

}
